package com.pzhu.controller;

import com.pzhu.service.LoginService;
import com.pzhu.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginByCookieServlet extends HttpServlet {
    LoginService loginService = new LoginServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
//        2.获取cookie
        if (req.getCookies() == null) { //为空时请求转发到page登录界面
            req.getRequestDispatcher("/page").forward(req, resp);
            System.out.println("cookie null");
            return;//请求转发之后需要return
        }
        for (Cookie reqCookie : req.getCookies()) {
            if ("userId".equals(reqCookie.getName())) {  //判断是否有id的cookie
                if ("".equals(reqCookie.getValue())) {     //获取cookie的id
                    req.getRequestDispatcher("/page").forward(req, resp);
                    System.out.println("cookie kong");
                    return;//请求转发之后需要return
                }

                //查询cookie数据是否在数据库中
                if (loginService.checkUserById(Integer.parseInt(reqCookie.getValue()))) {
//                    重置cookie TTL
                    System.out.println("查询cookie");
                    Cookie cookie = new Cookie("userId", reqCookie.getValue());
                    cookie.setMaxAge(7 * 24 * 3600);//设置生存时间 单位 /秒
                    cookie.setPath("/ss/lbc");//生效路径
//                  添加进resp，返回浏览器
                    resp.addCookie(cookie);
//                   添加session
                    HttpSession session = req.getSession();
                    session.setMaxInactiveInterval(1 * 1 * 3600);//设置生存时间 单位 /秒
                    System.out.println(loginService.selectUserById(Integer.parseInt(cookie.getValue())).getUid());
                    session.setAttribute("userId", loginService.selectUserById(Integer.parseInt(cookie.getValue()))
                    );
                    resp.sendRedirect("/ss/main");
                    System.out.println("cookie 通过");
                    return;//重定向之后return
                } else {
                    req.getRequestDispatcher("/page").forward(req, resp);
                    System.out.println("cookie 通过");
                    return;
                }
            }
        }
//        当遍历完cookie仍没有正确的数据，请求转发登录页面
        req.getRequestDispatcher("/page").forward(req, resp);
        return;
    }
}
